package com.sptan.framework.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.sptan.framework.constans.SsmpConstants;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.LocalDateTime;

/**
 * Description: 数据填充 .
 *
 * @author lp
 */
@Component
public class CustomMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId = getUserIdFromContext();
        this.setFieldValByName("delete_flag", false, metaObject);
        this.setFieldValByName("cuid", userId, metaObject);
        this.setFieldValByName("opuid", userId, metaObject);
        LocalDateTime now = LocalDateTime.now();
        this.setFieldValByName("ctime", now, metaObject);
        this.setFieldValByName("utime", now, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Long userId = getUserIdFromContext();
        this.setFieldValByName("opuid", userId, metaObject);
        this.setFieldValByName("utime", LocalDateTime.now(), metaObject);
    }

    private Long getUserIdFromContext() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request == null) {
            return 0L;
        }
        Long userId = (Long)request.getAttribute(SsmpConstants.REQUEST_ATTRIBUTE_USER_ID);
        if (userId != null) {
            return userId;
        } else {
            return 0L;
        }
    }
}
